package com.bang.concurrency.example.atomic;

import com.bang.concurrency.annotations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther: Bang
 * @Date: 2019/9/29 22:21
 * @Description: AtomicBoolean
 */
@Slf4j
@ThreadSafe
public class AtomicExample6 {

    private static int threadCount = 200;

    private static int clientCount = 5000;

    private static AtomicBoolean isHappened = new AtomicBoolean(false);


    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadCount);
        CountDownLatch countDownLatch = new CountDownLatch(clientCount);
        for (int index = 0; index < clientCount; index++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }

        countDownLatch.await();
        executorService.shutdown();
        log.error("isHappened = {}", isHappened.get());
    }

    private static void add() {
        if (isHappened.compareAndSet(false, true)) {
            log.info("execute");
        }
    }
}
